# -*- coding:utf-8 -*-

import redis
from Slave.config.slave_config import redis_host, redis_port, db, decode_responses, redis_password
from logger_config import logger_factory

logger = logger_factory()
redis_connect = None


def redis_connect_factory() -> redis.Redis:
    global redis_connect
    if redis_connect is None:
        redis_connect = redis.Redis(host=redis_host, port=redis_port, db=db, decode_responses=decode_responses,
                                    password=redis_password)
    return redis_connect


def redis_delete_key(key: str):
    global redis_connect
    if redis_connect is None:
        redis_connect = redis_connect_factory()
    return redis_connect.delete(key) == 1


def atomic_check_and_update(key, expected_value, new_value, ttl):
    """
    Automatically check if the value of a key matches the expcted value,
    and if so, update it to a new value and set a timeout
    :param key: Redis client instance, The key to check and update
    :param expected_value: The expected current value of the key
    :param new_value: The new value to set if the check passes
    :param ttl: Time_to_live(expiration time in seconds)
    :return: True if the values was updated, False otherwise
    """
    # Execute the lua script
    global redis_connect
    if redis_connect is None:
        redis_connect = redis_connect_factory()
    lua_script = '''
    if redis.call("GET", KEYS[1]) == ARGV[1] then
        redis.call("SET", KEYS[1], ARGV[2])
        redis.call("EXPIRE", KEYS[1], ARGV[3])
        return true
    else 
        return false
    end
    '''
    result = redis_connect.eval(lua_script, 1, key, expected_value, new_value, ttl)
    return bool(result)


def redis_change_expire_time(key: str, expire_time: str):
    global redis_connect
    if redis_connect is None:
        redis_connect = redis_connect_factory()
    lua_script = '''
    local key = KEYS[1]
    local new_expire_time = tonumber(ARGV[1])
    if redis.call('exists', key) == 0 then
        return false
    end
    local result = redis.call('expire', key, new_expire_time)
    return true
    '''
    # 加载lua脚本到Redis并获取SHA1检验和
    try:
        result = redis_connect.eval(lua_script, 1, key, expire_time)
        return bool(result)
    except Exception as e:
        logger.error(e)
        return False
